/*
 * @(#)CXSort.java
 * Copyright (c) 2008-2009 NEC Corporation
 */
package cn.bbs.ba.util;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.regex.Pattern;

import cn.bbs.ba.base.BaseDto;

/**
 * CXSort
 * @author ZHANGZZ
 * 		String[][] pkeys = {{"LEVEL","0"}};
 *		BASort sort = new BASort(pkeys);
 *		
 *		Collections.sort(yingjialist, sort);
 */

public class BASort implements Comparator {

    /**
     * 排序用的字段�
     */
    private String[][] keys;

    /**
     * �共几个字段排序
     */
    private final int KEY_SIZE;

    /**
     * ��f�W�^��子弹�F�b�N
     */
    private final Pattern numPattern = Pattern.compile("[^0-9]");

    /**
     * �R���g���N�排序类
     * @param pkeys
     */
    public BASort(final String[][] pkeys) {
        this.keys = pkeys;
        this.KEY_SIZE = pkeys.length;
    }

    public int compare(final Object po1, final Object po2) {

        /**
         * �排序
         */
        int count = 1;

        /**
         * 要比较的数据
         */
        BaseDto eo1 = (BaseDto)po1;
        BaseDto eo2 = (BaseDto)po2;

        /**
         * ��r����
         */
        while (true) {
            String[] key = this.keys[count - 1];
            String value1 = eo1.getString(key[0]);
            String value2 = eo2.getString(key[0]);
            if (count < this.KEY_SIZE && 0 == this.compValue(value1, value2)) {
                count = count + 1;
            }
            else if (0 == this.compValue(value1, value2)) {
                break;
            }
            else {
                count = count - 1;
                break;
            }
        }

        // �S���̗񂪓������ꍇ
        if (this.KEY_SIZE == count) {
            return 0;
        }

        String[] key = this.keys[count];
        String value1 = eo1.getString(key[0]);
        String value2 = eo2.getString(key[0]);
        if ("0".equals(key[1])) {
            return this.compValue(value1, value2);
        }
        else {
            return -this.compValue(value1, value2);
        }
    }

    /**
     * compValue
     * @param pvalue1
     * @param pvalue2
     * @return
     */
    private int compValue(final String pvalue1, final String pvalue2) {

        int retResult = 0;

        if (this.numPattern.matcher(pvalue1).find() || this.numPattern.matcher(pvalue2).find()
                || "".equals(pvalue1) || "".equals(pvalue2)) {
            retResult = pvalue1.compareTo(pvalue2);
        }
        else {
            BigDecimal compValue1 = new BigDecimal(pvalue1);
            BigDecimal compValue2 = new BigDecimal(pvalue2);
            retResult = compValue1.compareTo(compValue2);
        }

        return retResult;

    }

}
